package com.atguigu.fink.chapter01.tableapi;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.Json;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;


/**
 * @Author lzc
 * @Date 2022/11/28 09:06
 */
public class Flink03_TableApi_Kafka {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Schema schema = new Schema()
            .field("id", DataTypes.STRING())
            .field("ts", DataTypes.BIGINT())
            .field("vc", DataTypes.INT());
        
        // 连接到 kafka 的某个 topic
        tEnv
            .connect(
                new Kafka()
                    .version("universal")
                    .property("bootstrap.servers", "hadoop162:9092")
                    .property("group.id", "atguigu")
                    .topic("s1")
                    .startFromLatest()
            )
            .withFormat(new Csv())
            .withSchema(schema)
            .createTemporaryTable("sensor");
    
    
        Table sensor = tEnv.from("sensor");
        
        // 把表中的数据写出到 kafka 中
        tEnv
            .connect(
                new Kafka()
                    .version("universal")
                    .property("bootstrap.servers", "hadoop162:9092")
                    .topic("s2")
                    .sinkPartitionerRoundRobin()
            )
            //            .withFormat(new Csv().lineDelimiter(""))
            .withFormat(new Json())
            .withSchema(schema)
            .createTemporaryTable("s2_result");
        
        sensor.executeInsert("s2_result");
       
    }
}
